package com.irdstudio.efp.esb.api.rest.yed.loanManage;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.cus.service.facade.CompanyWhiteListService;
import com.irdstudio.efp.cus.service.vo.CompanyWhiteListVO;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.LoanInfArry;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.ReqPersonalLoanInfo;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RespPersonalLoanInfo;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.sed.PersonalLoanQryTypeEnum;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.rest.yed.req.ReqCompanyWhiteBean;
import com.irdstudio.efp.esb.api.rest.yed.resp.EnWhtlistInfArry;
import com.irdstudio.efp.esb.api.rest.yed.resp.RespCompanyWhiteBean;
import com.irdstudio.efp.esb.api.rest.yed.resp.WhtlistInfArry;
import com.irdstudio.efp.esb.api.service.sed.ploaninfo.PersonalLoanInfoService;
import com.irdstudio.efp.esb.api.service.yed.YedCompanyWhiteListService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.vo.AccLoanStatisticalInfo;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;



/**
 * 需求编号：【】
 * 问题编号：【】
 * 个人信息查询
 *
 * @author zhangxc
 * @version 0.1
 * @date 2020年8月1日16:17:58
 */
@RestController
@RequestMapping("/esb")
public class YedCompanyWhiteListController implements EsbController {

    private static Logger logger = LoggerFactory.getLogger(YedCompanyWhiteListController.class);

    @Autowired
    @Qualifier("companyWhiteListService")
    private CompanyWhiteListService companyWhiteListService;
    @Autowired
    private YedCompanyWhiteListService yedCompanyWhiteListService;

    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("reqCompanyWhiteBean")
    public ReqCompanyWhiteBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqCompanyWhiteBean.class, Feature.InternFieldNames);
    }

    /**
     * 处理请求
     *
     * @param esbReqServiceBean   esb请求对象
     * @param br1
     * @param br2
     * @param exception
     * @return
     */
    @PostMapping("/SERVICE_40130002_14")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqCompanyWhiteBean") ReqCompanyWhiteBean reqCompanyWhiteBean, BindingResult br2, Exception exception) throws ESBException, BizException {
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        logger.info("优e贷企业白名单查询开始,全局流水号为：[{}]",glblSrlNo);

        // 参数校验
        validateBean(esbReqServiceBean,br1, reqCompanyWhiteBean, br2, exception,logger);
        // 设置系统头对象
        setSysHeadFieldThreadLocal(esbReqServiceBean);

        //页码-当前查询第几页的数据
        String pageNo = reqCompanyWhiteBean.getPageIndex();
        //每页显示条数
        String pageSize = reqCompanyWhiteBean.getPageSize();

        //响应体
        RespCompanyWhiteBean respCompanyWhiteBean = new RespCompanyWhiteBean();

        if (Objects.nonNull(exception)) {
            //如果异常不为空，那么处理异常返回信息
            return yedCompanyWhiteListService.getEsbRespServiceBean(esbReqServiceBean, exception, pageNo, pageSize, respCompanyWhiteBean, EsbRetCodeStandard.JKYDCSJYBTG);
        }

        try {

            //根据查询类型封装不同条件的查询参数
            CompanyWhiteListVO companyWhiteListVO = yedCompanyWhiteListService.transferQueryParams(reqCompanyWhiteBean);

            //根据类型查询数据走不同的查询函数
            List<CompanyWhiteListVO> rtList = new ArrayList<CompanyWhiteListVO>();
            rtList = companyWhiteListService.queryCWhiteListByCondition(companyWhiteListVO);

            Integer totalSize = rtList.size();

            //处理授信查询结果
            rtList = yedCompanyWhiteListService.handleResultList(rtList,pageNo, pageSize);
            Map<String, AccLoanStatisticalInfo> accLoanStatisticalInfoMap = new HashMap<>();

            ArrayList<EnWhtlistInfArry> loanInfArries = new ArrayList<>();
            for (int i = 0; i < rtList.size(); i++) {
                loanInfArries.add(i, yedCompanyWhiteListService.getLoanInfArry(rtList.get(i)));
            }
            logger.info("企业白名单查询接口---开始处理要返回的数据");
            yedCompanyWhiteListService.setRespCompanyWhiteBean(pageNo, pageSize, respCompanyWhiteBean, totalSize, loanInfArries);
            logger.info("企业白名单查询接口---数据处理结束");

            respCompanyWhiteBean.setRetStCd(ESBConstant.SUCCESS);
            respCompanyWhiteBean.setRetMsg("查询成功");
            //返回报文
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSONObject.toJSONString(respCompanyWhiteBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero),
                    EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                    EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                    "查询成功");
        } catch (BizException ex) {
            logger.error("优e贷企业白名单接口出现异常，异常信息为：[{}]", ex.getMessage());
            ex.printStackTrace();
            return yedCompanyWhiteListService.getEsbRespServiceBean(esbReqServiceBean, ex, pageNo, pageSize, respCompanyWhiteBean, EsbRetCodeStandard.JKYDCSJYBTG);
        } catch (Exception e) {
            logger.error("优e贷企业白名单查询接口出现异常，异常信息为：[{}]", e.getMessage());
            e.printStackTrace();
            return yedCompanyWhiteListService.getEsbRespServiceBean(esbReqServiceBean, e, pageNo, pageSize, respCompanyWhiteBean, EsbRetCodeStandard.SJCLYC);

        }
    }



}
